{% extends theme_path('admin/base.html') %}

{% block title %}用户管理{% endblock %}

{% block content %}
<div class="p-6">
    <div class="bg-white rounded-lg shadow-sm">
        <div class="px-6 py-4 border-b">
            <div class="flex flex-col lg:flex-row justify-between items-stretch lg:items-center space-y-4 lg:space-y-0">
                <h2 class="text-xl font-bold">用户管理</h2>
                <div class="flex flex-col sm:flex-row items-stretch sm:items-center space-y-4 sm:space-y-0 sm:space-x-4 w-full lg:w-auto">
                    <form method="get" class="flex flex-col sm:flex-row items-stretch sm:items-center space-y-4 sm:space-y-0 sm:space-x-4 flex-1">
                        <select name="search_type" class="px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 w-full sm:w-auto">
                            <option value="username" {% if search_type != 'id' %}selected{% endif %}>用户名</option>
                            <option value="id" {% if search_type == 'id' %}selected{% endif %}>ID</option>
                        </select>
                        <div class="relative flex-1">
                            <input type="text" name="q" value="{{ search_query }}" placeholder="搜索用户..." class="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <svg class="h-5 w-5 text-gray-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                    <path fill-rule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clip-rule="evenodd" />
                                </svg>
                            </div>
                        </div>
                        <button type="submit" class="w-full sm:w-auto px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors duration-200">搜索</button>
                    </form>
                    <button onclick="showAddUserModal()" class="w-full sm:w-auto px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors duration-200">添加用户</button>
                </div>
            </div>
        </div>
            

            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-4 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                            <th class="px-4 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">昵称/用户名</th>
                            <th class="hidden sm:table-cell px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">邮箱</th>
                            <th class="hidden sm:table-cell px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">角色</th>
                            <th class="hidden sm:table-cell px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">注册时间</th>
                            <th class="hidden sm:table-cell px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">最后登录</th>
                            <th class="px-4 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        {% for user in pagination.items %}
                        <tr data-user-id="{{ user.id }}">
                            <td class="px-4 sm:px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ user.id }}</td>
                            <td class="px-4 sm:px-6 py-4">
                                <div class="flex items-center">
                                    <img src="{{ user.avatar }}" alt="avatar" class="w-8 h-8 rounded-full">
                                    <div class="ml-2">
                                        <a href="{{ url_for('user.author', id=user.id) }}" 
                                           class="text-sm font-medium text-gray-900 hover:text-blue-600">
                                            {{ user.nickname }}
                                        </a>
                                        <div class="text-xs text-gray-500">{{ user.username }}</div>
                                    </div>
                                </div>
                                <div class="sm:hidden mt-1 text-xs text-gray-500 space-y-1">
                                    <div>{{ user.email }}</div>
                                    <div class="flex items-center">
                                        <span>角色：</span>
                                        <span class="ml-1 px-2 py-0.5 rounded-full text-xs font-medium 
                                            {% if user.role == 'admin' %}
                                            bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200
                                            {% else %}
                                            bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300
                                            {% endif %}">
                                            {{ user.role }}
                                        </span>
                                    </div>
                                    <div>注册时间：{{ user.created_at.strftime('%Y-%m-%d') }}</div>
                                </div>
                            </td>
                            <td class="hidden sm:table-cell px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ user.email }}</td>
                            <td class="hidden sm:table-cell px-6 py-4 whitespace-nowrap">
                                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full {% if user.role == 'admin' %}bg-green-100 text-green-800{% else %}bg-gray-100 text-gray-800{% endif %}">
                                    {{ user.role }}
                                </span>
                            </td>
                            <td class="hidden sm:table-cell px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                {{ user.created_at.strftime('%Y-%m-%d %H:%M') }}
                            </td>
                            <!--<td class="hidden sm:table-cell px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                {{ user.last_login.strftime('%Y-%m-%d %H:%M') }}
                            </td>-->
                            <td class="px-4 sm:px-6 py-4 whitespace-nowrap text-sm">
                                <div class="flex items-center space-x-4">
                                    <button onclick="showEditUserModal({{ user.id }}, '{{ user.username }}', '{{ user.email }}', '{{ user.role }}', '{{ user.nickname }}')"
                                            class="text-blue-600 hover:text-blue-900">
                                        编辑
                                    </button>
                                    {% if user.id != current_user.id %}
                                    <button onclick="toggleUserRole({{ user.id }})"
                                            class="text-blue-600 hover:text-blue-900">
                                        {{ '降级为用户' if user.role == 'admin' else '提升为管理员' }}
                                    </button>
                                    <button onclick="deleteUser({{ user.id }})"
                                            class="text-red-600 hover:text-red-900">
                                        删除
                                    </button>
                                    {% endif %}
                                </div>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
            
            {% if pagination.pages > 1 %}
            <div class="px-6 py-4 mt-4 border-t">
                {% with endpoint='admin.users', kwargs={'q': search_query, 'search_type': search_type} %}
                {% include 'components/pagination.html' %}
                {% endwith %}
            </div>
            {% endif %}

    </div>
</div>

<div id="addUserModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center">
    <div class="bg-white rounded-lg shadow-xl w-full max-w-md mx-4">
        <div class="px-6 py-4 border-b">
            <h3 class="text-lg font-medium">添加用户</h3>
        </div>
        <form id="addUserForm" class="p-6 space-y-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                <input type="text" name="username" required
                       class="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                <input type="email" name="email" required
                       class="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                <input type="password" name="password" required
                       class="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">角色</label>
                <select name="role" 
                        class="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="user">普通用户</option>
                    <option value="admin">管理员</option>
                </select>
            </div>
        </form>
        <div class="px-6 py-4 border-t bg-gray-50 flex justify-end space-x-3">
            <button onclick="hideAddUserModal()"
                    class="px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg transition-colors duration-200">
                取消
            </button>
            <button onclick="addUser()"
                    class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors duration-200">
                添加
            </button>
        </div>
    </div>
</div>

<div id="editUserModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center">
    <div class="bg-white rounded-lg shadow-xl w-full max-w-md mx-4">
        <div class="px-6 py-4 border-b">
            <h3 class="text-lg font-medium">编辑用户</h3>
        </div>
        <form id="editUserForm" class="p-6 space-y-4">
            <input type="hidden" name="user_id">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                <input type="text" name="username" required
                       class="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">昵称</label>
                <input type="text" name="nickname"
                       class="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                       placeholder="不填写则显示为：昵称_用户名">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                <input type="email" name="email" required
                       class="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">新密码（留空则不修改）</label>
                <input type="password" name="password"
                       class="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">角色</label>
                <select name="role" 
                        class="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                        {% if user_id == current_user.id %}disabled{% endif %}>
                    <option value="user">普通用户</option>
                    <option value="admin">管理员</option>
                </select>
                {% if user_id == current_user.id %}
                <p class="mt-1 text-sm text-gray-500">不能修改自己的角色</p>
                {% endif %}
            </div>
        </form>
        <div class="px-6 py-4 border-t bg-gray-50 flex justify-end space-x-3">
            <button onclick="hideEditUserModal()"
                    class="px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg transition-colors duration-200">
                取消
            </button>
            <button onclick="updateUser()"
                    class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors duration-200">
                保存
            </button>
        </div>
    </div>
</div>

<script>
function toggleUserRole(userId) {
    showAlert('确定要更改此用户的角色吗？', 'warning', '确认操作', function() {
        fetch(`{{ admin_url }}/users/${userId}/toggle-role`, {
            method: 'POST',
            headers: {
                'X-CSRFToken': '{{ csrf_token() }}'
            }
        }).then(response => {
            if (response.ok) {
                showAlert('角色更改成功', 'success', '成功');
                setTimeout(() => location.reload(), 10);  // 10ms后刷新页面
            } else {
                showAlert('操作失败', 'error', '错误');
            }
        }).catch(error => {
            showAlert('操作失败，请稍后重试', 'error', '错误');
            console.error('Error:', error);
        });
    });
}

function deleteUser(userId) {
    showAlert('确定要删除此用户吗？此操作不可恢复！', 'warning', '确认删除', function() {
        fetch(`{{ admin_url }}/users/${userId}`, {
            method: 'DELETE',
            headers: {
                'X-CSRFToken': '{{ csrf_token() }}'
            }
        }).then(response => {
            if (response.ok) {
                const userRow = document.querySelector(`tr[data-user-id="${userId}"]`);
                if (userRow) {
                    userRow.remove();
                    showAlert('用户删除成功', 'success', '成功');
                } else {
                    location.reload();
                }
            } else {
                response.json().then(data => {
                    showAlert(data.error, 'error', '错误');
                });
            }
        }).catch(error => {
            showAlert('删除失败，请稍后重试', 'error', '错误');
            console.error('Error:', error);
        });
    });
}

function addUser() {
    const form = document.getElementById('addUserForm');
    const formData = new FormData(form);
    
    fetch('{{ admin_url }}/users/add', {
        method: 'POST',
        headers: {
            'X-CSRFToken': '{{ csrf_token() }}'
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            showAlert(data.error, 'error', '错误');
        } else {
            showAlert('用户添加成功', 'success', '成功');
            setTimeout(() => location.reload(), 1500);
        }
    });
}

function updateUser() {
    const form = document.getElementById('editUserForm');
    const userId = form.user_id.value;
    const formData = new FormData(form);
    
    fetch(`{{ admin_url }}/users/${userId}/edit`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': '{{ csrf_token() }}'
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            showAlert(data.error, 'error', '错误');
        } else {
            showAlert('用户信息更新成功', 'success', '成功');
            setTimeout(() => location.reload(), 650);
        }
    });
}

function showAddUserModal() {
    document.getElementById('addUserModal').classList.remove('hidden');
    document.getElementById('addUserModal').classList.add('flex');
}

function hideAddUserModal() {
    document.getElementById('addUserModal').classList.add('hidden');
    document.getElementById('addUserModal').classList.remove('flex');
    document.getElementById('addUserForm').reset();
}

function showEditUserModal(userId, username, email, role, nickname) {
    const form = document.getElementById('editUserForm');
    form.user_id.value = userId;
    form.username.value = username;
    form.email.value = email;
    form.role.value = role;
    form.nickname.value = nickname || '';
    
    const roleSelect = form.querySelector('select[name="role"]');
    if (userId === {{ current_user.id }}) {
        roleSelect.disabled = true;
        roleSelect.parentElement.querySelector('p')?.classList.remove('hidden');
    } else {
        roleSelect.disabled = false;
        roleSelect.parentElement.querySelector('p')?.classList.add('hidden');
    }
    
    document.getElementById('editUserModal').classList.remove('hidden');
    document.getElementById('editUserModal').classList.add('flex');
}

function hideEditUserModal() {
    document.getElementById('editUserModal').classList.add('hidden');
    document.getElementById('editUserModal').classList.remove('flex');
    document.getElementById('editUserForm').reset();
}
</script>
{% endblock %} 